<template>
  <ul class='list'>
    <li class="item"
      v-for="item in lletters"
      :key="item"
      :ref="item"
      @click="handleLetterClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      >
      {{item}}
    </li>
  </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop // 第0项才是dom元素,A字母的位置距离
  },
  computed: {
    lletters () {
      const lletters = []
      for (let i in this.cities) {
        lletters.push(i)
      }
      // console.log(lletters)
      return lletters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      // 开始触摸时，修改touchStatus状态为true
      this.touchStatus = true
      // console.log(this.touchStatus)
    },
    handleTouchMove (e) {
      // 只有在touchStaus等于ture是才去处理事件
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => { // 节流
          const touchY = e.touches[0].clientY - this.startY// 手指滑动的位置距离
          const index = Math.floor((touchY - this.startY) / 20)// 除以每个字母的高度,得到每个字母对应的字母下标
          if (index >= 0 && index <= this.lletters.length) {
            this.$emit('change', this.lletters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      // 离开触摸时，修改touchStatus状态为false
      this.touchStatus = false
      // console.log(this.touchStatus)
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
  .list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    .item
      text-align center
      line-height .4rem
      color $bgColor
</style>
